/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.appleframework.web;

import java.util.HashMap;
import java.util.Map;
import jregex.Matcher;
import jregex.Pattern;
import org.appleframework.Apple;

/**
 *
 * @author zhujg
 */
public class Router {

  static Pattern routePattern = new Pattern("^({method}GET|POST|PUT|DELETE|OPTIONS|HEAD|\\*)?\\s+({path}/[^\\s]*)\\s+({action}[^\\s(]+)({params}.+)?$");
  public static Map<String, Route> routes = new HashMap<String, Route>();

  public static void load(){
		routes.clear();
		String content = Apple.router.contentToString();
		for(String line : content.split("\n")){
			line = line.trim().replaceAll("\\s+", " ");
			if(line.length()==0 || line.startsWith("#")){
				continue;
			}
			Matcher matcher = routePattern.matcher(line);
			if(matcher.matches()){
				Route route = new Route();
				route.method=matcher.group("method");
				route.path = matcher.group("path");
				route.action=matcher.group("action");
				routes.put(route.method+route.path, route);
			}
		}
	}

  public static Route route(String route) {
    return routes.get(route);
  }

  public static class Route {

    public String method;
    public String action;
    public String namespace;
    public String path;

    @Override
    public String toString() {
      return "method:" + method + " path:" + path + " action:" + action;
    }
  }
}
